from django.contrib import admin
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import User, Specialization


@admin.register(User)
class UserAdmin(BaseUserAdmin):

    fieldsets = (
        (None, {'fields': ('username', 'password')}),
        ('Personal info', {'fields': ('first_name', 'second_name', 'last_name')}),
        ('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
        ('Specialization',
         {'fields': ('main_specialization', 'additional_specializations', 'employment_fraction')}),
    )
    add_fieldsets = (
        (None, {
            'classes': ('wide',),
            'fields': ('username', 'password1', 'password2',
                       'first_name', 'second_name', 'last_name', 'employment_fraction',
                       'groups', 'user_permissions'),
        }),
    )
    list_display = ('username', 'first_name', 'second_name', 'last_name', 'employment_fraction',
                    'main_specialization', 'get_additional_specializations',
                    'get_is_doctor', 'get_is_hr', 'get_is_chief')
    search_fields = ('username', 'first_name', 'second_name', 'last_name',
                     'main_specialization__specialization', 'additional_specializations__specialization')
    ordering = ('last_name', 'first_name', 'main_specialization')

    def get_is_doctor(self, obj):
        return obj.groups.filter(name='Врач').exists()
    get_is_doctor.short_description = 'Врач'
    get_is_doctor.boolean = True

    def get_is_hr(self, obj):
        return obj.groups.filter(name='Отдел кадров').exists()
    get_is_hr.short_description = 'Отдел кадров'
    get_is_hr.boolean = True

    def get_is_chief(self, obj):
        return obj.groups.filter(name='Руководитель референс-центра').exists()
    get_is_chief.short_description = 'Руководитель'
    get_is_chief.boolean = True

    def get_additional_specializations(self, obj):
        return ", ".join([spec.specialization for spec in obj.additional_specializations.all()])
    get_additional_specializations.short_description = 'Дополнительные специализации'


@admin.register(Specialization)
class SpecializationAdmin(admin.ModelAdmin):
    list_display = ('specialization',)
    search_fields = ('specialization', )
